package com.maslyk.invitation;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;

import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;

import org.apache.log4j.Logger;
import org.apache.myfaces.application.ActionListenerImpl;

import com.maslyk.invitation.enums.LocalNames;
import com.maslyk.invitation.to.SessionDataTO;

public class CustomActionListener extends ActionListenerImpl
{
	Logger log = Logger.getLogger(CustomActionListener.class);
	
    public CustomActionListener()
    {
        super();
    }

    @Override
    public void processAction(final ActionEvent event)
    {
        try
        {
            String styleClass = (String) event.getComponent().getAttributes().get("styleClass");
            if(styleClass != null && styleClass.indexOf("back") != -1)
            {
                SessionDataTO sessionData = (SessionDataTO) BeanService.getSessionScopeBean("SessionDataTO");
                sessionData.popViewID();
            }

            super.processAction(event);
        }
        catch (Throwable t)
        {
        	Throwable rootCause = getCauseException(t);
        	log.error(t,t);
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,LocalNames.LOGICAL_ERROR_HEADER , rootCause.getMessage()));
            FacesContext.getCurrentInstance().renderResponse();
        }
    }

    public Throwable getCauseException(Throwable t)
    {
    	Throwable result = t.getCause();
    	
    	while(result.getCause()!= null)
    		result = result.getCause();
    	
    	return result;
    }
    
    public static String getStackTrace(Throwable aThrowable)
    {
        final Writer result = new StringWriter();
        final PrintWriter printWriter = new PrintWriter(result);
        aThrowable.printStackTrace(printWriter);
        return result.toString();
     }
}